package com.yooim.chat;

import java.util.Hashtable;
import java.util.Iterator;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Message;

import sun.rmi.runtime.NewThreadAction;


public class ChatBot implements Runnable {

	Hashtable<String, String> chatQueues = new Hashtable<String, String>(); 
	// Holds the actual queues
    Hashtable<String, Chat> chatSessions = new Hashtable<String, Chat>();
	// Holds the Chat objects

	public static void main(String[] args) {

		ChatBot chat = new ChatBot();
		chat.go();
		chat.startNew();
		chat.sendMessage("ajay@localhost", "Hey there!");

	}
	
	public void startNew() {
	    try{
            conn = new XMPPConnection(config);
            conn.connect();
            conn.login("pat", "pat");
            //createConversation("ajay@localhost");
            Roster roster = conn.getRoster();
            Iterator<RosterEntry> iter = 
                       roster.getEntries().iterator();
            while (iter.hasNext()) {
                RosterEntry entry = (RosterEntry) iter.next();
                createConversation(entry.getUser());
            }

        } catch (Exception e){
            System.out.println("StartNew Exception");
            e.printStackTrace();
        }

        System.out.println("Done.");

	}

	public void addToRoster(String targetUser, String targetName){
        Roster roster = conn.getRoster();
        try {
            roster.createEntry(targetUser, targetName, null);
            createConversation(targetUser);
        } catch (XMPPException e){
            e.printStackTrace();
        }
    }

	 public String getMessages(String targetUser){
	        String queue = chatQueues.get(targetUser).toString();
	        chatQueues.put(targetUser, "");
	        return queue;        
	    }

	 public void sendMessage(String targetUser, String theMessage){
	        Chat theChat = (Chat)chatSessions.get(targetUser);
	        String theQueue = (String)chatQueues.get(targetUser);
	        try {
	            theChat.sendMessage(theMessage);
	            chatQueues.put(targetUser, theQueue + "<br />You: "+theMessage);
	        } catch (Exception e){
	            e.printStackTrace();
	        }
	    }

		 public void removeFromRoster(String targetUser){
		        Roster roster = conn.getRoster();
		        try {
		            RosterEntry entry = roster.getEntry(targetUser);
		            roster.removeEntry(entry);

		            chatSessions.remove(targetUser);
		            chatQueues.remove(targetUser);

		        } catch (XMPPException e){
		            e.printStackTrace();
		        }
		    }

		 
		 public String getRoster(){
		        Roster roster = conn.getRoster();
		        String returnStr = "";
		        Iterator<RosterEntry> iter = roster.getEntries().iterator();
		        while (iter.hasNext()) {
		            RosterEntry entry = (RosterEntry) iter.next();
		            returnStr = returnStr + "<span id='"+entry.getUser()+
		                   "' onclick='changeUser(\""+entry.getUser()+
		                   "\", \""+entry.getName()+"\")'>"+entry.getName() + 
		                   "</span><br />";
		        }
		        return returnStr;
		    }

    private void createConversation(String target){
        try {
            chatQueues.put(target, "");

            Chat chat = conn.getChatManager().createChat(target,
                    new MessageListener() {
                public void processMessage(Chat chat, Message message) {
                    try {
                        chat.sendMessage("Got "+message.getBody());}               
                    catch (Exception e){ 
                        e.printStackTrace();
                    }

                    String currentQueue = chatQueues.get(chat.getParticipant());
                    chatQueues.put(chat.getParticipant(), currentQueue 
					  + "<br />" + message.getBody());
                    System.out.println(chat.getParticipant() + " said " + 
					  message.getBody());
                } 
            }
            ); 

            chatSessions.put(target, chat);    
        } catch (Exception e){
            System.out.println("Create Conversation Exception");
            e.printStackTrace();
        }
    }


    ConnectionConfiguration config = new ConnectionConfiguration("localhost",5222);
	XMPPConnection conn;
	public void stop()
	{
		conn.disconnect();
	}
	
	public void run()
	{
		Thread current = Thread.currentThread();
		while(botThread == current)
		{
			try{
				Thread.sleep(2000);
			}
			catch(InterruptedException e)
			{
				
			}
		}
		
	}
	
	Thread botThread;
	String queue = "start";

	public void go()
	{
		if(botThread == null)
		{
			botThread = new Thread(this, "IMTHread");
			botThread.start();
		}
	}
}
